﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using ecdl.demo.model.expression;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml.Packaging;

namespace ecdl.demo.model.word {
    public abstract class WordExpression : expression.Expression{

        public override ExpressionState Evaluate(ExpressionContext context) {
            var document = context.GetContext<WordprocessingDocument>();
            if (document != null){
                return Evaluate(document);
            } else {
                return Fail(String.Format("Die %s kann nur im Kontext eines Worddokuments verwendet werden.", this.GetType().Name));
            }
        }

        protected IEnumerable<Paragraph> GetAllParagraphs(WordprocessingDocument document) {
            return document.MainDocumentPart.RootElement.Descendants<Paragraph>();
        }

        protected string GetText(Paragraph p) {
            StringBuilder buffer = new StringBuilder();
            foreach (var textElement in p.Descendants<Text>()) {
                buffer.Append(textElement.InnerText);
            }
            return buffer.ToString();
        }

        protected abstract ExpressionState Evaluate(WordprocessingDocument document);
    }
}
